package com.yang.studentsapp.activity;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.audiofx.BassBoost;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.hyphenate.exceptions.HyphenateException;
import com.yang.studentsapp.EaseUser;
import com.yang.studentsapp.R;
import com.yang.studentsapp.bean.DemoDBManager;
import com.yang.studentsapp.presenter.IViewLogin;
import com.yang.studentsapp.presenter.SettingPresenterImpl;
import com.yang.studentsapp.ui.MyAppliction;
import com.yang.studentsapp.utils.EaseCommonUtils;
import com.yang.studentsapp.utils.NetUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by ${Ян-Вэнь-Чао} on 2016/9/30.
 */
public class LoginActivity extends AppCompatActivity {
  EditText editName, editPwd;
    SettingPresenterImpl presenter;
    ProgressDialog dialog;
    private boolean autoLogin = false;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (EMClient.getInstance().isLoggedInBefore()) {
            autoLogin = true;
            startActivity(new Intent(LoginActivity.this, MainActivity.class));

            return;
        }
        setContentView(R.layout.activity_login);
        presenter = new SettingPresenterImpl();
        editName = (EditText) findViewById(R.id.edit_user_name);
        editPwd = (EditText) findViewById(R.id.edit_password);
editName.addTextChangedListener(new TextWatcher() {
    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        editPwd.setText(null);
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {

    }
});
    }

    public void login(View view) {
//        if (!EaseCommonUtils.isNetWorkConnected(this)) {
//            Toast.makeText(this, R.string.network_isnot_available, Toast.LENGTH_SHORT).show();
//            return;
//        }
        if (NetUtils.isConnected(LoginActivity.this)) {
            if (isContent()) {
                return;
            }
        } else {
            Toast.makeText(this,"网络未连接！！！",Toast.LENGTH_SHORT).show();
            final AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("提示");
            builder.setMessage("是否打开网络?");
            builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    NetUtils.openSetting(LoginActivity.this);

                }
            });
            builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    builder.create().dismiss();
                }
            });
            AlertDialog Adialog = builder.create();
            Adialog.show();

        }

    }

    private boolean isContent() {
        String name = getText(editName);
        if (TextUtils.isEmpty(name)) {
            Toast.makeText(this, "手机号不能为空", Toast.LENGTH_SHORT).show();
            return true;
        }
        String pwd = getText(editPwd);
        if (TextUtils.isEmpty(pwd)) {
            Toast.makeText(this, "密码不能为空", Toast.LENGTH_SHORT).show();
            return true;
        }

//登录之前关闭它,以确保DemoDB不重叠
        DemoDBManager.getInstance().closeDB();

      presenter.login(name, pwd, new IViewLogin() {
          @Override
          public void error(final String error) {
              dialog.dismiss();
              runOnUiThread(new Runnable() {
                  public void run() {
                      dialog.dismiss();
                      Toast.makeText(getApplicationContext(), getString(R.string.Login_failed) + error,
                              Toast.LENGTH_SHORT).show();
                  }
              });
          }

          @Override
          public void start(String msg) {
              if (dialog == null) {
                  dialog = new ProgressDialog(LoginActivity.this);
                  dialog.setMessage(msg);
                  dialog.setCanceledOnTouchOutside(true);
              }
              dialog.show();
          }

          @Override
          public void onSuccess(String data) {
              dialog.dismiss();
              EMClient.getInstance().groupManager().loadAllGroups();
              EMClient.getInstance().chatManager().loadAllConversations();
              getFriends();

              Toast.makeText(LoginActivity.this, data, Toast.LENGTH_SHORT).show();
              startActivity(new Intent(LoginActivity.this, MainActivity.class));
              finish();
          }
      });
        return false;
    }


    private  void  getFriends(){
        try {
            List<String> usernames = EMClient.getInstance().contactManager().getAllContactsFromServer();
            Map<String ,EaseUser> users=new HashMap<String ,EaseUser>();
            for(String username:usernames){
                EaseUser user=new EaseUser(username);
                users.put(username, user);


            }

            MyAppliction.getInstance().setContactList(users);


        } catch (HyphenateException e) {
            e.printStackTrace();
        }

    }

    private String getText(EditText editText) {
        if (editText == null) {
        return null;
        }
        return editText.getText().toString().trim();
    }

    public void register(View view) {
        startActivity(new Intent(LoginActivity.this, RegisterActivity.class));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        LoginActivity.this.finish();

    }
}
